//
//  ZNXAxisView.m
//  ZNChart
//
//  Created by Yim on 16/9/24.
//  Copyright © 2016年 LQ. All rights reserved.
//

#import "ZNXAxisView.h"
#import "UIView+LQExtension.h"
#import "ZNDraw.h"

@interface ZNXAxisView ()
{
    UILabel *_firstLabel;
    
}

/**  *  x轴标题数组    */
@property (nonatomic , strong) NSMutableArray *titleLabelArray;


/**  *  画图模型    */
@property (nonatomic , strong) ZNDraw *currentChart;

/**  *  text高度    */
@property (nonatomic , assign) CGFloat textHeight;

/**  *  图表高度    */
@property (nonatomic , assign) CGFloat chartHeight;

@end

@implementation ZNXAxisView

- (NSMutableArray *)titleLabelArray
{
    if (!_titleLabelArray) {
        _titleLabelArray = [NSMutableArray array];
    }
    return _titleLabelArray;
}


- (void)awakeFromNib
{
    self.autoresizingMask = UIViewAutoresizingNone;
    
}

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        self.textFont = [UIFont systemFontOfSize:12];
        CGFloat textHeight = [@"x" sizeWithAttributes:@{NSFontAttributeName : self.textFont}].height;
        self.textHeight = textHeight;
        self.backgroundColor = [UIColor clearColor];
        
    }
    return self;
}


- (void)drawRect:(CGRect)rect {
    
    if (self.points.count == 0) {
        [self drawView];
        return;
    }else
    {
        [self drawView];
    [self drawPointAndLine:nil isChartLine:self.isChartLine];
    }
}


- (void) drawPointAndLine:(ZNDraw *)draw isChartLine:(BOOL)chartLine
{
    self.chartHeight = self.height - self.textHeight - _xAxisTextGap - self.topMargin;
    
    
    if (self.currentChart.isChartLine) {  // 画折线
        
        if (self.currentChart.isChartViewFill) { // 画线，空白处填充
            
            
            CGContextRef ctx = UIGraphicsGetCurrentContext();
            
            self.currentChart.path = [[UIBezierPath alloc] init];
            
            CGPoint start = CGPointMake(self.pointGap, self.height - self.xAxisTextGap - self.textHeight);
            
            [self.currentChart.path moveToPoint:start];
            
            for (int i = 0; i < self.currentChart.pointArray.count; i++) {
                
                NSNumber *value = self.currentChart.pointArray[i];
                
                
                NSString *title = [self decimalwithFormat:@"0.00" floatV:value.floatValue];
                
                // 判断title的值，整数或者小数
                if (![self isPureFloat:title]) {
                    title = [NSString stringWithFormat:@"%.0f", title.floatValue];
                }
                
                if (value.floatValue < 0) {
                    value = @(0);
                }
               
                CGPoint center = CGPointMake((i+1)*self.pointGap, self.chartHeight - value.floatValue/self.yAxisMaxValue * self.chartHeight + self.topMargin);
                
                if (self.yAxisMaxValue * self.chartHeight == 0) {
                    center = CGPointMake((i+1)*self.pointGap, self.chartHeight + self.topMargin);
                }
                
                [self.currentChart.path addLineToPoint:center];
                // 显示点
                if (self.currentChart.isShowPoint) {
                    [self addPointCenter:center andTag:i];
                }
                
                // 添加point处的Label
                if (self.isShowPointLabel) {
                    
                    [self addLabelWithTitle:title atLocation:center andTag:i];
                    
                }
                
            }
            
            CGPoint end = CGPointMake(self.currentChart.pointArray.count*self.pointGap, self.height - self.xAxisTextGap - self.textHeight);
            
            [self.currentChart.path addLineToPoint:end];
            
            [self.currentChart.lineColor set];
            // 将路径添加到图形上下文
            CGContextAddPath(ctx, self.currentChart.path.CGPath);
            // 渲染
            CGContextFillPath(ctx);
            
        }else{  // 画线，只有线，没有填充色
            
            CGContextRef ctx = UIGraphicsGetCurrentContext();
            
            self.currentChart.path = [[UIBezierPath alloc] init];
            
            NSNumber *startValue = self.currentChart.pointArray[0];
//            NSLog(@"start = %@",startValue);
            CGPoint start = CGPointMake(self.pointGap, self.chartHeight - startValue.floatValue/self.yAxisMaxValue * self.chartHeight + self.topMargin);
//            NSLog(@"\nstart = %f y = %f",start.x,start.y);
            
            [self.currentChart.path moveToPoint:start];
            
            for (int i = 0; i < self.currentChart.pointArray.count; i++) {
                
                NSNumber *value = self.currentChart.pointArray[i];
                NSString *title = [self decimalwithFormat:@"0.00" floatV:value.floatValue];
                
                // 判断title的值，整数或者小数
                if (![self isPureFloat:title]) {
                    title = [NSString stringWithFormat:@"%.0f", title.floatValue];
                }
//                 NSLog(@"...%@",title);
                CGPoint center = CGPointMake((i+1)*self.pointGap, self.chartHeight - value.floatValue/self.yAxisMaxValue * self.chartHeight + self.topMargin);
                
                
                if (i < self.currentChart.pointArray.count - 1) {
                    
                    NSNumber *value = self.currentChart.pointArray[i+1];
                    
                    CGPoint center = CGPointMake((i+2)*self.pointGap, self.chartHeight - value.floatValue/self.yAxisMaxValue * self.chartHeight + self.topMargin);
                    
                    if (self.yAxisMaxValue * self.chartHeight == 0) {
                        center = CGPointMake((i+1)*self.pointGap, self.chartHeight + self.topMargin);
                    }
                    [self.currentChart.path addLineToPoint:center];
                    
                }
           
                // 显示点
                if (self.currentChart.isShowPoint) {
                    [self addPointCenter:center andTag:i];
                }
                
                // 添加point处的Label
                if (self.isShowPointLabel) {
                    
                    [self addLabelWithTitle:title atLocation:center andTag:i];
                    
                }
                /**
                 *  画柱状图
                 */
                if (self.isShowPillar) {
                    
                    NSDictionary *attribute = @{NSFontAttributeName : self.textFont};
                    CGSize textSize = [title sizeWithAttributes:attribute];
                    CGFloat width = textSize.width <= 15 ? 10: 10;
//                    NSLog(@"width = %f",width);
                    CGRect rect = CGRectMake(center.x - width / 2, center.y, width, self.chartHeight + self.topMargin - center.y);
                    
                    UIBezierPath *path = [UIBezierPath bezierPathWithRect:rect];
                    [_pillarColor setFill];
                    [path fill];
                    
                }
                
            }
            
            [[self.currentChart.lineColor colorWithAlphaComponent:0.7] set];
            // 将路径添加到图形上下文
            CGContextAddPath(ctx, self.currentChart.path.CGPath);
            // 渲染
            CGContextStrokePath(ctx);
        }
        

        
    }else
    {
        // 只画点和label
        for (int i = 0; i < self.currentChart.pointArray.count; i++) {
            NSNumber *value = self.currentChart.pointArray[i];
//            NSLog(@"%@",value);
            NSString *title = [self decimalwithFormat:@"0.00" floatV:value.floatValue];
            
            // 判断title的值，整数或者小数
            if (![self isPureFloat:title]) {
                title = [NSString stringWithFormat:@"%.0f", title.floatValue];
            }
            
            if (value.floatValue < 0) {
                value = @(0);
            }
            
            CGPoint center = CGPointMake((i+1)*self.pointGap, self.chartHeight - value.floatValue/self.yAxisMaxValue * self.chartHeight + self.topMargin);
            
            if (self.yAxisMaxValue * self.chartHeight == 0) {
                center = CGPointMake((i+1)*self.pointGap, self.chartHeight + self.topMargin);
            }
            
            /**
             *  画柱状图
             */
            if (self.isShowPillar) {
                
                NSDictionary *attribute = @{NSFontAttributeName : self.textFont};
                CGSize textSize = [title sizeWithAttributes:attribute];
                CGFloat width = textSize.width <= 15 ? 10: 15;
                
                CGRect rect = CGRectMake(center.x - width / 2, center.y, width, self.chartHeight + self.topMargin - center.y);
                
                
                
                UIBezierPath *path = [UIBezierPath bezierPathWithRect:rect];
                [_pillarColor setFill];
                [path fill];
                
            }
            // 添加点
            [self addPointCenter:center andTag:i];
            
            // 添加point处的Label
            if (self.isShowPointLabel) {
                
                [self addLabelWithTitle:title atLocation:center andTag:i];
                
            }
            
        }
    }
}

- (void)drawView
{
    self.backgroundColor = [UIColor clearColor];
    
    CGFloat textHeight = [@"x" sizeWithAttributes:@{NSFontAttributeName : self.textFont}].height;
    self.textHeight = textHeight;
   
    // 移除先前存在的所有视图
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
    }
    
    
    UIView *yAxis = [UIView new];
    yAxis.backgroundColor = self.axisColor;
    yAxis.x = 0;
    yAxis.y = self.height - self.xAxisTextGap - self.textHeight - 1;
    yAxis.width = self.width;
    yAxis.height = 1;
    [self addSubview:yAxis];
    
    
    CGFloat yAxisHeight = self.height - self.textHeight - self.xAxisTextGap;
    
    
    CGFloat allSeparateHeight = yAxisHeight - self.topMargin;
    
    CGFloat separateGap = (allSeparateHeight - (self.yAxisNumber) * self.textHeight) / self.yAxisNumber;
    CGFloat separateHeight = 0.8;
    if (self.showSeparate) {
        
        for (int i = 0; i < self.yAxisNumber; i ++) {
            
            UIView *separate = [[UIView alloc] init];
            separate.x = 0;
            separate.y = yAxisHeight - (self.textHeight + separateGap) * (i + 1);
            separate.width = self.width;
            separate.height = separateHeight;
            separate.backgroundColor = self.separateColor;
            [self addSubview:separate];
        }
    }
    
    if (self.xAxisTitleArray.count == 0) {
        
    }else
    {
        for (int i = 0; i < self.xAxisTitleArray.count; i ++) {
            NSString *title = [NSString stringWithFormat:@"%@",self.xAxisTitleArray[i]];
            UILabel *label = [[UILabel alloc] init];
            CGSize labelSize = [title sizeWithAttributes:@{NSFontAttributeName : self.textFont}];
            label.x = (i + 1) * self.pointGap - labelSize.width / 2;
            label.y = self.height - labelSize.height;
            label.size = labelSize;
            
            label.text = title;
            label.font = self.textFont;
            label.textColor = self.textColor;
            
            if (i == 0) {
                _firstLabel = label;
            }
            [self addSubview:label];
        }
        
        
        // 如果Label的文字有重叠，那么隐藏
        for (int i = 0; i < self.titleLabelArray.count; i++) {
            
            UILabel *label = self.titleLabelArray[i];
            
            CGFloat maxX = CGRectGetMaxX(_firstLabel.frame);
            
            if (self.isShowHeadAndTail == NO) {
                if (i != 0) {
                    if ((maxX + 3) > label.x) {
                        label.hidden = YES;
                    }else{
                        label.hidden = NO;
                        _firstLabel = label;
                    }
                }else {
                    if (_firstLabel.x < 0) {
                        _firstLabel.x = 0;
                    }
                }
            }else{
                
                if (i > 0 && i < self.titleLabelArray.count - 1) {
                    
                    label.hidden = YES;
                    
                }else if(i == 0){
                    
                    if (_firstLabel.x < 0) {
                        _firstLabel.x = 0;
                    }
                    
                }else{
                    
                    if (CGRectGetMaxX(label.frame) > self.width) {
                        
                        label.x = self.width - label.width;
                    }
                }
            }
        }
    }
    
    
  
    
    self.currentChart = [ZNDraw new];
    self.currentChart.lineColor = self.lineColor;
    self.currentChart.lineWidth = self.lineWidth;
    self.currentChart.isChartLine = self.isChartLine;
    self.currentChart.isRound = self.isRound;
    self.currentChart.showPoint = self.showPoint;
    self.currentChart.pointColor = self.lineColor;
    self.currentChart.pointArray = self.points;

   
}

- (NSString *) decimalwithFormat:(NSString *)format  floatV:(float)floatV
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    
    [numberFormatter setPositiveFormat:format];
    
    return  [numberFormatter stringFromNumber:[NSNumber numberWithFloat:floatV]];
}

// 判断是小数还是整数
- (BOOL)isPureFloat:(NSString *)numStr
{
    //    NSScanner* scan = [NSScanner scannerWithString:string];
    //    float val;
    //    return [scan scanFloat:&val] && [scan isAtEnd];
    
    CGFloat num = [numStr floatValue];
    
    int i = num;
    
    CGFloat result = num - i;
    
    // 当不等于0时，是小数
    return result != 0;
}

- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

// 添加pointLabel的方法
- (void)addLabelWithTitle:(NSString *)title atLocation:(CGPoint)location andTag:(NSInteger)i {
    
    UIButton *button = [[UIButton alloc] init];
    
    if (self.isPercent) {
        [button setTitle:[NSString stringWithFormat:@"%@%%", title] forState:UIControlStateNormal];
    }else{
        [button setTitle:title forState:UIControlStateNormal];
    }
    
    [button setTitleColor:self.textColor forState:UIControlStateNormal];
    button.titleLabel.font = self.textFont;
    //    label.font = self.textFont;
    button.layer.backgroundColor = [UIColor clearColor].CGColor;
    button.tag = i;
    button.userInteractionEnabled = self.isPointUserInteractionEnabled;
    
    NSDictionary *attr = @{NSFontAttributeName : self.textFont};
    CGSize buttonSize = [button.currentTitle sizeWithAttributes:attr];
    
    button.width = buttonSize.width;
    button.height = buttonSize.height;
    button.x = location.x - button.width / 2;
    button.y = location.y - button.height - 3;
    [button addTarget:self action:@selector(pointDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:button];
}

- (void) addPointCenter:(CGPoint)center andTag:(int)i
{
    UIButton *button = [[UIButton alloc] init];
    button.tag = i;
    [button setBackgroundImage:[self imageWithColor:self.currentChart.pointColor] forState:UIControlStateNormal];
    [button setBackgroundImage:[self imageWithColor:self.currentChart.pointSelectedColor] forState:UIControlStateSelected];
    button.size = CGSizeMake(6, 6);
    button.center = center;
    if (self.currentChart.isRound) {
        button.layer.cornerRadius = 3;
        button.layer.masksToBounds = YES;
    }
    
//    button.userInteractionEnabled = self.isPointUserInteractionEnabled;
    
    [button addTarget:self action:@selector(pointDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    //            [self.pointButtonArray addObject:button];
    
    if (button.userInteractionEnabled) {
        if (i == 0) {
            [self pointDidClicked:button];
        }
    }
    
    [self addSubview:button];
}

- (void) pointDidClicked: (UIButton *)sender
{
    if ([self.delegate respondsToSelector:@selector(buttonClickEvent:andIndex:andView:)]) {
        [self.delegate buttonClickEvent:sender andIndex:sender.tag andView:self];
    }
}



@end
